package com.chatmcp.mcprouter.server;

import com.chatmcp.mcprouter.config.ApiServerConfig;
import com.chatmcp.mcprouter.service.CacheService;
import com.chatmcp.mcprouter.util.DatabaseUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * API服务器启动器
 * 负责启动MCP API服务器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ApiServer implements CommandLineRunner {

    private final ApiServerConfig apiServerConfig;
    private final CacheService cacheService;
    private final DatabaseUtil databaseUtil;

    @Value("${app.use_db:false}")
    private boolean useDb;

    @Value("${app.api_db_name:}")
    private String apiDbName;

    @Value("${app.use_cache:false}")
    private boolean useCache;

    @Value("${app.cache_name:}")
    private String cacheName;

    @Override
    public void run(String... args) throws Exception {
        // 检查是否需要启动API服务器
        if (args.length > 0 && "api".equals(args[0])) {
            // 初始化配置
            initConfig(args);
            // 启动服务器
            startServer();
        }
    }

    /**
     * 初始化配置
     */
    private void initConfig(String... args) {
        log.info("API服务器正在初始化配置...");
        
        // 解析命令行参数中的配置文件路径
        String configFile = ".env.properties";
        for (int i = 0; i < args.length - 1; i++) {
            if ("-c".equals(args[i]) || "--config".equals(args[i])) {
                configFile = args[i + 1];
                break;
            }
        }
        
        log.info("使用配置文件: {}", configFile);
        
        // 初始化数据库连接
        if (useDb && !apiDbName.isEmpty()) {
            try {
                databaseUtil.initDatabase(apiDbName);
                log.info("数据库 {} 初始化成功", apiDbName);
            } catch (Exception e) {
                log.error("数据库 {} 初始化失败: {}", apiDbName, e.getMessage());
            }
        }
        
        // 初始化缓存
        if (useCache && "redis".equals(cacheName)) {
            try {
                cacheService.initCache(cacheName);
                log.info("缓存 {} 初始化成功", cacheName);
            } catch (Exception e) {
                log.error("缓存 {} 初始化失败: {}", cacheName, e.getMessage());
            }
        }
    }

    /**
     * 启动API服务器
     */
    private void startServer() {
        int port = apiServerConfig.getPort();
        if (port == 0) {
            port = 8027; // 默认端口
        }
        
        log.info("API服务器启动于端口: {}", port);
        
        // Spring Boot已经启动了Web服务器
        log.info("API服务器启动成功");
    }
} 